var Manages = function() {


    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();
    var checkName_url = $('.checkName_url').val();
    var setRecommend_url = $('.setRecommend_url').val();

    var contentData_url = $('.contentData_url').val();


    // 七牛
    var upload_element = 'cover-image'; // 上传按钮的上级元素ID
    var upload_btn = 'upload-cover-btn'; // 上传按钮的ID
    var field = $('#' + upload_btn).attr('data-field');
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = $('#' + upload_btn).attr('data-max_file_size');
    var extensions = $('#' + upload_btn).attr('data-extensions');
    var multi = $('#' + upload_btn).attr('data-multi');


    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 60px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "name"},
                    {"data": "typeId"},
                    {"data": "area"},
                    {"data": "categoryId"},
                    {"data": "phone"},
                    {
                        //"width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            if(row.isRecommend == 1){
                                html += '<button type="button" class="btn yellow doRecommend-btn" data-value="2">取消推荐</button>';
                            }else{
                                html += '<button type="button" class="btn purple doRecommend-btn" data-value="1">首页推荐</button>';
                            }

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [2, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 1, 3, 4, 5, 6]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                    var city = $('input[name=city]').val();
                    if(city){
                        //$("#city").find("option:contains('"+city+"')").attr("selected", true);
                        get_xian($("#city"));
                    }
                }
            });
        } else {
            // 百度地图API功能
            //创建Map实例
            var map = new BMap.Map("map_container");
            //初始化武汉坐标
            var point = new BMap.Point(114.405492,30.502934);
            var offsetY = 200;
            //地图平移缩放控件：默认左上方
            map.addControl(new BMap.NavigationControl());
            //比例尺控件，默认位于地图左下方，显示地图的比例关系
            map.addControl(new BMap.ScaleControl());
            map.centerAndZoom(point,12);
            //添加鼠标滚动缩放
            map.enableScrollWheelZoom(true);
            //设置标注的图标

            //显示地址信息窗口
            var marker = new BMap.Marker(point);
            //把标注添加到地图上
            map.addOverlay(marker);

            //地址解析类
            var gc = new BMap.Geocoder();
            function showLocationInfo(pt, rs){
                var addComp = rs.addressComponents;
                $("#longitude").val(pt.lng);
                $("#latitude").val(pt.lat);
                console.log('经纬度：'+pt.lat+' '+pt.lng);
                $("#add-text1").val(pt.lat+','+pt.lng);
            }

            //删除标注
            function deletePoint(){
                var allOverlay = map.getOverlays();
                for (var i = 0; i < allOverlay.length; i++){
                    map.removeOverlay(allOverlay[i]);
                }
            }

            //根据选择框或输入框获取地址
            var _area={
                //keyword:'',
                _address:$("#address"),
                unChecked:function(val){
                    return (val==''||typeof (val)=='undefined'||val==null||
                        val=='省份'||val=='地级市'||val=='市、县级市')?false:true;
                },
                list:function(){
                    var _joinArea='';
                    if(_area.unChecked(this._address.val())){
                        _joinArea+=' '+this._address.val();
                        //_joinArea=this._address.val();
                    }
                    return _joinArea;
                },
                init:function(){
                    //绑定百度地图
                    var _this=_area.list();
                    //定义local
                    var local = new BMap.LocalSearch(map, {
                        renderOptions: {
                            map: map,
                            panel: "results",//结果容器id
                            autoViewport: true,   //自动结果标注
                            selectFirstResult: true  , //指定到第一个目标
                            enableRouteSearchBox: true,
                            enableRouteInfo:true
                        },
                        pageCapacity: 1
                    });

                    local.setSearchCompleteCallback(function (searchResult) {
                        var poi = searchResult.getPoi(0);
                        //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
                        map.centerAndZoom(poi.point, 12);
                        gc.getLocation(poi.point, function(rs){
                            showLocationInfo(poi.point, rs);
                        });
                    });
                    local.search(_this);
                }
            }

            //全局变量：存储address字符串长度做判断
            var _thisLength='';
            $("#address").keydown(function(){
                _thisLength=$(this).val().length;
            })
            $("#address").keyup(function(){
                var _newLength=$(this).val().length;
                var timer=setTimeout(function(){
                    if(_thisLength<=_newLength){
                        deletePoint();
                        _area.init();
                    }
                    else{
                        clearTimeout(timer);
                    }
                },1000);
            })
            $("#address").blur(function(){
                deletePoint();
                _area.init();
            })
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 首页推荐
        table.on('click', '.doRecommend-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);
            var isRecommend = $(this).data('value');

            event.preventDefault();
            var url = setRecommend_url;
            var data = {
                'table': 'Manages',
                'id':id,
                'isRecommend':isRecommend
            };
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType : 'json',
                success: function (data) {
                    layer.msg(data.msg);
                    if(data.code == 1){
                        //table.DataTable().ajax.reload();
                        table.DataTable().draw(false);
                    }
                }
            });
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    /**
     * 七牛初始化
     */
    var initUploader = function () {
        if($('#' + upload_element).length <= 0){
            return ;
        }

        var url = "";
        var qiniupercent = "";
        var uploader = upload_element;
        var pickfiles = upload_btn;
        if(max_file_size == '' || max_file_size == undefined){
            max_file_size = '1MB';
        }
        if(extensions == '' || extensions == undefined){
            extensions = 'jpg,jpeg,gif,png';
        }
        if(multi == 'false'){
            multi = false;
        }else{
            multi = true;
        }

        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                uploaderReadyForImg(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
            }
        });
    };

    var uploaderReadyForImg = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            container: uploader,      //上传按钮的上级元素ID
            drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                if(multi) {
                                    // 多图
                                    var $item = '';
                                    $item += '<span class="multi-image">';
                                    $item += '<input type="hidden" name="imgIds" value="'+data.image_id+'">';
                                    $item += '<input type="hidden" name="'+field+'" value="'+sourceLink+'">';
                                    $item += '<img class="exist-image" src="'+sourceLink+'" alt="" />';
                                    $item += '<img class="del" src="/public/static/pages/image/del.png" alt="">';
                                    $item += '</span>';

                                    $('#' + upload_btn).before($item);
                                } else {
                                    // 单图
                                    // 删除原图
                                    var img_id = $('#' + upload_btn).find('input[name=imgId]').val();
                                    var img_url = $('#' + upload_btn).find('img').attr('src');
                                    delOriginalImg(img_id, img_url);

                                    $('#' + upload_btn).find('img').attr('src', sourceLink);
                                    $('#' + upload_btn).find('input').val(sourceLink);
                                    $('#' + upload_btn).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                                // imgcount++;
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };

    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };

    // 表单提交
    var submitForm = function(btnObj) {
        var form = document.getElementById("ajax-form");
        var _this = btnObj;

        if(!form.id.value) {
            if(form.townId.value == 0) {
                layer.msg('请选择所在地');
                return;
            }
        }
        if(form.name.value.trim() == '') {
            layer.msg('请输入分类名称');
            form.name.focus();
            return;
        }
        if(form.name.value.length > 40){
            layer.msg('分类名称最多为40个字符');
            form.name.focus();
            return false;
        }
        if(form.typeId.value.trim() == '') {
            layer.msg('请选择主体类型');
            return;
        }
        if(form.categoryId.value.trim() == '') {
            layer.msg('请选择主体类目');
            return;
        }
        if(form.coverImg.value.trim() == ''){
            layer.msg('请上传Logo');
            return false;
        }
        if(form.address.value.trim()=='') {
            layer.msg('请输入地址');
            form.address.focus();
            return;
        }
        var mobile = $('#phone').val();
        if(mobile){
            var mobile_reg = /^1(3|4|5|6|7|8)[0-9]\d{8}$/;
            if(!mobile_reg.test(mobile)){
                layer.msg('手机号格式不正确');
                return;
            }
        }

        var _data = $(form).serializeObject();
        _data.imgUrl = _data.coverImg;
        if (_data.isRecommend && _data.isRecommend == 'on') {
            _data.isRecommend = 1;
        } else {
            _data.isRecommend = 2;
        }
        _this.prop("disabled", true);

        $.ajax({
            url : save_url,
            type : 'post',
            dataType : 'json',
            contentType : "application/json; charset=utf-8",
            data : JSON.stringify(_data),
        }).done(function(data) {
            _this.prop("disabled", false);
            if (data.code == 1) {
                layer.msg('保存成功');
                window.location.href = data.url;
            } else {
                layer.msg(data.msg);
            }
        });
    };


    return {
        init: function() {
            initTable();
            initUploader();

            this.onEvent();
        },

        onEvent: function() {

            // 表单提交
            $('#form-submit').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(!form.id.value) {
                    if(form.townId.value == 0) {
                        layer.msg('请选择所在地');
                        return;
                    }
                }
                if(form.name.value.trim() == '') {
                    layer.msg('请输入分类名称');
                    form.name.focus();
                    return;
                }
                if(form.name.value.length > 40){
                    layer.msg('分类名称最多为40个字符');
                    form.name.focus();
                    return false;
                }

                var name = $('#name').val();
                var ori_name = $('#name').attr('data-name');

                if(name != ori_name){
                    var url = checkName_url;
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: {'name': name},
                        dataType : 'json',
                        success: function (data) {
                            if(data.status == 1){
                                layer.msg('该名称已经存在！');
                                $('#name').focus();
                                return false;
                            }else{
                                submitForm(_this);
                            }
                        }
                    });
                    return false;
                }

                submitForm(_this);
            });
        }

    };

}();

jQuery(document).ready(function() {
    Manages.init();

});
